<template>
    <div class="el-transfer" v-if="isMounted">
        <div class="el-transfer-panel">
            <p class="el-transfer-panel__header">
                <label class="el-checkbox">
                    <el-checkbox v-model="checkAll"
                                 :indeterminate="isIndeterminate"
                                 @change="handleCheckAllChange">
                        {{ titleArray[titleIndex] }}
                        <span v-if="props.serverApi">{{ countLeftSelect }}/{{ state.total }}</span>
                        <span v-else>已选 {{ countLeftSelect }}</span>
                    </el-checkbox>
                </label>
            </p>
            <div class="el-transfer-panel__body">
                <el-checkbox-group
                    v-model="checkedCities"
                    class="el-transfer-panel__list ele-transfer-panel__list"
                    @change="handleCheckedCitiesChange"
                    :infinite-scroll-disabled="disabledScroll"
                     v-infinite-scroll="loadStaffList" >

                    <label class="el-checkbox el-transfer-panel__item"
                           v-for="item in state.list"
                           :key="item[props.label]">
                        <el-checkbox :label="item[props.label]">
                            <span class="pb9" style="display: inline-block">{{ item[props.name] }}</span>
                        </el-checkbox>
                    </label>

                    <label class="el-checkbox el-transfer-panel__item"
                           style="text-align: center;padding: 0"
                           @click="loadStaffList"
                           v-if="!disabledScroll && !loadingLeftPage">
                        <span>
                            <span class="pr3">
                                <el-icon><ele-Pointer/></el-icon>
                            </span>
                            点击加载
                        </span>
                    </label>
                    <label class="el-checkbox el-transfer-panel__item"
                           style="text-align: center;padding: 0"
                           v-if="disabledScroll && loadingLeftPage">
                        <span class="pr4 pt1">
                            <el-icon><ele-Loading /></el-icon>
                        </span>
                        正在加载中...
                    </label>

                </el-checkbox-group>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import {computed, reactive, ref, onMounted, toRefs, watch, nextTick} from "vue";
import {ElMessage} from "element-plus";

/** 此处引入 */
const emits = defineEmits(['update:modelValue'])
/** 定义组件入参 */
const props = defineProps({
    data: {
        type: Array,
        default: []
    },
    /** 服务调用 APi */
    serverApi: Function,
    /** 显示名称 */
    name:{
        type: String,
        default: 'name'
    },
    /**  */
    label:{
        type: String,
        default: 'id'
    },
    /** 默认选中的值 */
    modelValue: {
        type: Object,
        default: () => []
    },
})

// const {dialog} = toRefs(props)

/*
    加载更多 - disabledScroll false and loading false
    正在加载中.. - disabledScroll true and loading true
 */
const disabledScroll = ref(true);

// 加载控制器
const loadingLeftPage = ref(false)

// 状态数据
const state = reactive<any>({
    size: 10,// 页容
    current: 0,// 当前页
    total: 0,// 记录条数据
    pages: 1,// 共多少页
    list: [],// 列表 - 使用深度拷贝
})

// 左侧全选框
const checkAll = ref(false)
// 左侧全选框 - 半选状态
const isIndeterminate = ref(false)
// 选中的数据
let checkedCities = computed({
    get: () => props.modelValue,
    set: (val) => emits('update:modelValue', val)
})
const titleArray = ['全选','清除']
const titleIndex = ref(0)

// 加载员工列表
const loadStaffList = async () => {
    // 关闭滚动加载
    disabledScroll.value = true
    // 判断分页数据，控制关闭加载
    if (state.current === state.pages){
        disabledScroll.value = true
        return
    }
    // 开启加载显示
    loadingLeftPage.value = true
    try {
      const {data} = await (props.serverApi as any)()
      state.list = data
      disabledScroll.value = true
        // // 组装对象
        // const temp: any = {'size': state.size, 'current': state.current + 1}
        // // 请求分页
        // const {data} = await (props.serverApi as any)(temp)
        // // 解构
        // const {records, total, size, current, pages} = data
        // // 回填
        // state.total = total
        // state.page = size
        // state.pages = pages
        // state.current = current
        // state.list.push(...records)
        // // 再次检查 - 判断分页数据，控制关闭加载
        // if (current === pages) {
        //     disabledScroll.value = true
        // } else {
        //     // 开启滚动加载 - 当成功时才可以再开启 - 防止死循环
        //     disabledScroll.value = false
        // }
    }catch (e:any) {
        console.log(e);
        ElMessage.error(e.message)
        // 当失败之后 - 等待 10 秒再次开启 - 会出现死循环
        // setTimeout(()=>{
        //     disabledScroll.value = false
        // },10000)
    }
    // 关闭加载显示
    loadingLeftPage.value = false
}

/** 如果传入 serverApi 就开启滚动加载 */
if (props.serverApi) {
    loadStaffList()
}

// 点击列表的勾选框
const handleCheckedCitiesChange = (value: string[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === state.list.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < state.list.length
}

// 点击全选框
const handleCheckAllChange = (val:any) =>{
    const temp:any = []
    if (val){
        state.list.forEach((fe:any)=>{
            temp.push(fe[props.label])
        })
    }
    checkedCities.value = temp
    isIndeterminate.value = false
}

// 监听选中的数量
let countLeftSelect = computed(()=>{
    // 选中的长度
    let temp = checkedCities.value.length || 0
    // 列表长度
    let max = state.list.length || 0
    // 当前选中的数量为 0
    if (0 >= temp || 0 >= max) {
        titleIndex.value = 0
        isIndeterminate.value = false
        checkAll.value = false
    } else if (temp > 0) {
        // 当前有选中时改为半选
        isIndeterminate.value = true
        if (temp === max) {
            // 当前全选
            titleIndex.value = 1
            isIndeterminate.value = false
            checkAll.value = true
        }
    }
    return temp
})

// 页面加载完成再显示
const isMounted = ref(false);
onMounted(() => {
  isMounted.value = true
  if (props.data) {
    state.list = Object.assign([], props.data)
  }
})

</script>

<style scoped lang="scss">

:deep(.el-icon) {
    margin-right: 0 !important;
}

.ele-transfer-panel__list{
    height: 278px !important;
    overflow: hidden auto !important;
    padding: 0 !important;
    border: none !important;
    margin: 0 !important;
    box-sizing: border-box !important;
}

</style>
